package com.scsj.supermarket.view.fragment.fivepagemodel;

import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AutoCompleteTextView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.orhanobut.logger.Logger;
import com.scsj.supermarket.R;
import com.scsj.supermarket.adapter.homeadapter.HomeRecycleViewAdapter;
import com.scsj.supermarket.base.IndexBase;
import com.scsj.supermarket.bean.IndexBean;
import com.scsj.supermarket.bean.IndexGoodsListBean;
import com.scsj.supermarket.bean.IndexMarketBean;
import com.scsj.supermarket.bean.homebean.HomeRecommendBean;
import com.scsj.supermarket.event.FirstEvent;
import com.scsj.supermarket.presenter.IndexPresenter;
import com.scsj.supermarket.utils.RxBus;
import com.scsj.supermarket.utils.SkipUtils;
import com.scsj.supermarket.view.fragment.basemodel.BaseFragment;
import com.zaaach.citypicker.CityPicker;
import com.zaaach.citypicker.adapter.OnPickListener;
import com.zaaach.citypicker.model.City;
import com.zaaach.citypicker.model.HotCity;
import com.zaaach.citypicker.model.LocateState;
import com.zaaach.citypicker.model.LocatedCity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import es.dmoral.toasty.Toasty;
import okhttp3.RequestBody;

/**
 * 新框架，新首页
 */

public class MyHomeFragment extends BaseFragment implements View.OnClickListener, IndexBase.IView {

    private RecyclerView home_rv;
    private HomeRecycleViewAdapter adapter;
    private double mDistanceY = 0;
    private LinearLayout serch_ll;
    public static List<?> images = new ArrayList<>();
    public static List<String> titles = new ArrayList<>();
    private View view;
    private LinearLayout mTopSelectCityLl;
    private AutoCompleteTextView mSearchAt;
    private LinearLayout mTopSearchLl;
    private LinearLayout mTopQrCodeLl;
    private LinearLayout mTopMessageLl;
    private TextView mTopSelectCityTv;
    private ImageView mTopEaraArrowDown;
    private ImageView mTopQrCodeIv;
    private ImageView mTopMessageIv;
    private IndexPresenter presenter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View inflate = inflater.inflate(R.layout.fragment_my_home, null);

        presenter = new IndexPresenter(this);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("cityName", "郑州市");
        RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json;charset=utf-8"), jsonObject.toString());

        presenter.deliverAllList(body);

        JSONObject jsonObject1 = new JSONObject();
        jsonObject1.put("cityName", "郑州市");
        jsonObject1.put("latitude", "34");
        jsonObject1.put("longitude", "118");
        RequestBody body1 = RequestBody.create(okhttp3.MediaType.parse("application/json;charset=utf-8"), jsonObject1.toString());

        presenter.deliverMarketList(body1);

        initView(inflate, null);
        initListener();
        initData();
        return inflate;
    }

    @Override
    protected void initView(View view, Bundle savedInstanceState) {
        home_rv = view.findViewById(R.id.home_rv);
        home_rv.setLayoutManager(new LinearLayoutManager(getHoldingActivity()));
        home_rv.setNestedScrollingEnabled(false);
        serch_ll = view.findViewById(R.id.serch_ll);
        mTopSelectCityLl = (LinearLayout) view.findViewById(R.id.top_select_city_ll);
        mSearchAt = (AutoCompleteTextView) view.findViewById(R.id.search_at);
        mTopSearchLl = (LinearLayout) view.findViewById(R.id.top_search_ll);
        mTopQrCodeLl = (LinearLayout) view.findViewById(R.id.top_qr_code_ll);
        mTopMessageLl = (LinearLayout) view.findViewById(R.id.top_message_ll);
        mTopMessageLl.setOnClickListener(this);
        mTopSelectCityTv = (TextView) view.findViewById(R.id.top_select_city_tv);
        mTopEaraArrowDown = (ImageView) view.findViewById(R.id.top_eara_arrow_down);
        mTopQrCodeIv = (ImageView) view.findViewById(R.id.top_qr_code_iv);
        mTopMessageIv = (ImageView) view.findViewById(R.id.top_message_iv);
    }

    @Override
    protected void initListener() {
        mTopSelectCityLl.setOnClickListener(this);
        mSearchAt.setOnClickListener(this);
        mTopSearchLl.setOnClickListener(this);
        mTopQrCodeLl.setOnClickListener(this);
        mTopMessageLl.setOnClickListener(this);
    }

    @Override
    protected void initData() {

    }

    @Override
    protected int getLayoutId() {
        return 0;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            default:
                break;
            case R.id.top_select_city_ll://选择城市
                SkipUtils.toSelectCity(getHoldingActivity());
//                choiceCity();
                break;
            case R.id.search_at://搜索栏
                SkipUtils.toSerch(getHoldingActivity());
                break;
            case R.id.top_qr_code_ll://二维码

                SkipUtils.toScanCode(getHoldingActivity());
                break;
            case R.id.top_message_ll://消息
                SkipUtils.toMessage(getHoldingActivity());
                break;
        }
    }

    private void choiceCity() {

        List<HotCity> hotCities = new ArrayList<>();
        hotCities.add(new HotCity("北京", "北京", "101010100"));
        hotCities.add(new HotCity("上海", "上海", "101020100"));
        hotCities.add(new HotCity("广州", "广东", "101280101"));
        hotCities.add(new HotCity("深圳", "广东", "101280601"));
        hotCities.add(new HotCity("杭州", "浙江", "101210101"));

        CityPicker.getInstance()
                .setFragmentManager(getHoldingActivity().getSupportFragmentManager())    //此方法必须调用
                .enableAnimation(true)    //启用动画效果
//                        .setAnimationStyle(anim)	//自定义动画
                .setLocatedCity(new LocatedCity("郑州", "河南", "101210101"))  //APP自身已定位的城市，默认为null（定位失败）
                .setHotCities(hotCities)    //指定热门城市
                .setOnPickListener(new OnPickListener() {
                    @Override
                    public void onPick(int position, City data) {
                        if (data != null) {
//                            Toast.makeText(getHoldingActivity(), data.getName(), Toast.LENGTH_SHORT).show();
                            Logger.e("Name=>"+data.getName()+"|Code=>"+data.getCode()+"|Pinyin=>"+
                                    data.getPinyin()+"|Province=>"+data.getProvince()+"|Section=>"+data.getSection());
                            Toasty.normal(getHoldingActivity(),"Name=>"+data.getName()+"|Code=>"+data.getCode()+"|Pinyin=>"+
                                    data.getPinyin()+"|Province=>"+data.getProvince()+"|Section=>"+data.getSection()).show();
                        }

                    }

                    @Override
                    public void onLocate() {
                        //开始定位，这里模拟一下定位
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                //定位完成之后更新数据
                                CityPicker.getInstance()
                                        .locateComplete(new LocatedCity("深圳", "广东", "101280601"), LocateState.SUCCESS);
                            }
                        }, 2000);
                    }
                })
                .show();
    }

    @Override
    public void showSuccessMsg(String s) {
        Toasty.info(getHoldingActivity(), s).show();
    }

    @Override
    public void showErrorMsg(String s) {
        Toasty.info(getHoldingActivity(), s).show();
    }

    @Override
    public void setAllData(IndexBean indexBean) {
        adapter = new HomeRecycleViewAdapter(getHoldingActivity(), indexBean);
        home_rv.setAdapter(adapter);
        //搜索栏渐变
        home_rv.setOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                //防止item乱跳
                //staggeredGridLayoutManager.invalidateSpanAssignments();
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                //滑动的距离
                mDistanceY += dy;
                //toolbar的高度
                int toolbarHeight = serch_ll.getBottom();
                com.orhanobut.logger.Logger.d("toolbarHeight==>" + toolbarHeight);

                //当滑动的距离 <= toolbar高度的时候，改变Toolbar背景色的透明度，达到渐变的效果
                if (mDistanceY == 0) {
                    mTopSelectCityTv.setTextColor(Color.WHITE);
                    mTopEaraArrowDown.setBackgroundResource(R.mipmap.down_arrow_white);
                    mTopQrCodeIv.setBackgroundResource(R.mipmap.ic_white_scan);
                    mTopMessageIv.setBackgroundResource(R.mipmap.ic_message);
                    serch_ll.setBackgroundColor(Color.argb((int) 0, 255, 255, 255));
                } else if (mDistanceY <= toolbarHeight && mDistanceY > 0) {
                    float scale = (float) mDistanceY / toolbarHeight;
                    float alpha = scale * 255;
                    serch_ll.setBackgroundColor(Color.argb((int) alpha, 255, 255, 255));
                    mTopSelectCityTv.setTextColor(Color.argb((int) alpha, 110, 110, 110));

                    com.orhanobut.logger.Logger.d("mDistanceY==>" + mDistanceY);
                } else {
                    //将标题栏的颜色设置为完全不透明状态
                    serch_ll.setBackgroundColor(Color.argb((int) 255, 255, 255, 255));
                    mTopSelectCityTv.setTextColor(Color.argb((int) 255, 110, 110, 110));
                    mTopEaraArrowDown.setBackgroundResource(R.mipmap.down_arrow_gray);
                    mTopQrCodeIv.setBackgroundResource(R.mipmap.ic_gray_scan);
                    mTopMessageIv.setBackgroundResource(R.mipmap.ic_message_gray);
                }
            }
        });
    }

    @Override
    public void setIndexMarketData(IndexMarketBean indexMarketBean) {
        adapter.setShops(indexMarketBean);
    }
}
